<script setup>
const props = defineProps({
  open: Boolean,
});
const emit = defineEmits(["close", "openEdit"]);

import AppIcon from "@/components/AppIcon.vue";
import { reactive, ref, watch, defineExpose } from "vue";
import * as home from "@/api/home/index";
import { message } from "ant-design-vue";

const groups = ref([]);
// const open = ref([]);
const urlsByGroup = reactive({});
// const isModalVisible = ref(false);
const searchValue = ref("");
const searchResults = ref([]);
const urlForm = reactive({
  url: "",
  name: "",
  icon: "",
  group_id: null,
  description: "",
});

const editUrl = (url) => {
  Object.assign(urlForm, url);
  emit("openEdit", url, searchValue.value);
};
const deleteUrl = async (data) => {
  await home.delListByGroupId(data);
  fetchGroups();
  performSearch(searchValue.value);
  emit("refreshList");
};

const fetchGroups = async () => {
  try {
    const response = await home.getGroup();
    groups.value = response.data;
    groups.value.forEach((group) => {
      fetchUrlsByGroup(group.id);
    });
  } catch (error) {
    message.error("获取分组失败", error);
  }
};
const fetchUrlsByGroup = async (group_id) => {
  try {
    const response = await home.getGroupByID(group_id);
    urlsByGroup[group_id] = response.data;
  } catch (error) {
    message.error(`获取分组 ${group_id} 的网址失败`, error);
  }
};

const performSearch = async (value) => {
  if (!value) {
    searchResults.value = [];
    return;
  }

  try {
    const response = await home.searchGroup(value);
    if (response.code === 200) {
      searchResults.value = response.data;
    } else {
      searchResults.value = [];
    }
  } catch (error) {
    message.error("搜索失败:", error);
    searchResults.value = [];
  }
};

const handleCancel = () => {
  emit("close"); // 触发关闭事件
};

const resetSearchValue = () => {
  searchValue.value = "";
};

watch(searchValue, async (newValue) => {
  await performSearch(newValue);
});

defineExpose({ performSearch, resetSearchValue });
</script>

<template>
  <a-modal :open="open" title="搜索网站" width="1000px" @cancel="handleCancel">
    <template #footer> </template>
    <a-flex vertical gap="large">
      <a-input-search
        v-model:value="searchValue"
        placeholder="输入搜索内容（名称、网址、描述）"
        enter-button
        size="large"
        :allow-clear="true"
      />
      <a-card v-if="searchValue.length > 0" class="search_card icon_group_card">
        <h2>搜索结果</h2>
        <a-flex wrap="wrap" gap="large">
          <AppIcon
            v-for="url in searchResults"
            :key="url.id"
            :url="url.url"
            :icon="url.icon"
            :name="url.name"
            :description="url.description"
            @edit="editUrl(url)"
            @delete="deleteUrl(url)"
          />
        </a-flex>
        <p v-if="searchResults.length === 0">没有找到匹配的内容。</p>
      </a-card>
    </a-flex>
  </a-modal>
</template>

<style scoped></style>
